import tkinter as tk
import time
import json
from pathlib import Path


def show_classification_text():
    # 读取JSON配置文件
    def load_time_texts(json_path="time_texts.json"):
        if not Path(json_path).exists():
            default_data = {
                "0分:10秒": "已运行10秒",
                "0分:30秒": "注意休息",
                "1分:00秒": "已运行1分钟",
                "1分:30秒": "继续保持"
            }
            with open(json_path, "w", encoding="utf-8") as f:
                json.dump(default_data, f, ensure_ascii=False, indent=2)
            return default_data

        with open(json_path, "r", encoding="utf-8") as f:
            return json.load(f)

    # 加载时间-文本配置并转换为秒数
    time_texts = load_time_texts()
    timed_events = {}
    for time_str, text in time_texts.items():
        try:
            minutes, seconds = time_str.split("分:")
            seconds = seconds.replace("秒", "").strip()
            total_seconds = int(minutes) * 60 + int(seconds)
            timed_events[total_seconds] = text
        except Exception as e:
            print(f"JSON格式错误，跳过无效条目 {time_str}：{e}")

    # 创建主窗口
    root = tk.Tk()
    root.title("分类分级显示")

    # 窗口属性设置（透明背景）
    root.overrideredirect(True)
    root.attributes("-topmost", True)
    root.attributes("-alpha", 1.0)
    root.attributes("-transparentcolor", "white")
    root.config(bg="white")

    start_time = int(time.time())

    # 字体设置
    custom_font = ("SimHei", 20, "bold")
    event_font = ("SimHei", 16)
    element_width = 60
    element_height = 30

    # 创建主框架
    main_frame = tk.Frame(root, bg="white")
    main_frame.pack(padx=10, pady=5)

    # 标题
    tk.Label(main_frame, text="分类分级", font=custom_font, bg="white").pack()

    # 时间显示框架
    time_frame = tk.Frame(main_frame, bg="white")
    time_frame.pack(pady=5)

    # "已过去"文本
    tk.Label(time_frame, text="已过去", font=custom_font, bg="white").pack(side=tk.LEFT)

    # 分钟滚动组件
    minute_canvas = tk.Canvas(
        time_frame,
        width=element_width,
        height=element_height,
        bg="white",
        highlightthickness=0
    )
    minute_canvas.pack(side=tk.LEFT)
    tk.Label(time_frame, text="分", font=custom_font, bg="white", fg="#FF0000").pack(side=tk.LEFT)

    # 秒钟滚动组件
    second_canvas = tk.Canvas(
        time_frame,
        width=element_width,
        height=element_height,
        bg="white",
        highlightthickness=0
    )
    second_canvas.pack(side=tk.LEFT)
    tk.Label(time_frame, text="秒", font=custom_font, bg="white", fg="#FFFF00").pack(side=tk.LEFT)

    # 事件文本显示区域（垂直增量显示）
    events_frame = tk.Frame(main_frame, bg="white")
    events_frame.pack(pady=5, fill=tk.X)

    # 存储状态变量
    prev_minutes = 0
    prev_seconds = 0
    current_minute_text = None
    current_second_text = None
    displayed_events = set()
    event_counter = 0  # 用于跟踪事件数量，控制垂直位置

    def scroll_element(canvas, value, color, prev_value, current_text_id):
        """通用滚动动画函数"""
        if value != prev_value:
            if current_text_id:
                canvas.delete(current_text_id)

            final_y = element_height * 0.7
            new_text = canvas.create_text(
                element_width / 2,
                -element_height / 2,
                text=str(value),
                font=custom_font,
                fill=color
            )

            def animate():
                x, y = canvas.coords(new_text)
                remaining = final_y - y
                if remaining > 2:
                    canvas.move(new_text, 0, 2)
                    root.after(10, animate)
                elif remaining > 0:
                    canvas.move(new_text, 0, remaining)

            animate()
            return value, new_text
        return prev_value, current_text_id

    def add_event_text(text):
        """垂直增量显示新事件文本（从上方滑入）"""
        nonlocal event_counter

        # 创建事件文本标签
        event_label = tk.Label(
            events_frame,
            text=text,
            font=event_font,
            bg="white",
            fg="#0000FF"
        )
        event_label.pack(anchor=tk.W, pady=2)  # 左对齐，增加垂直间距

        # 初始位置在可视区域上方（隐藏）
        event_label.place(x=0, y=-20)  # 负坐标隐藏在上方
        event_label.lift()  # 确保在最上层

        # 滑入动画
        def slide_in(pos=0):
            if pos < 20:  # 移动到目标位置（20像素）
                event_label.place(x=0, y=pos - 20)
                root.after(10, slide_in, pos + 2)
            else:
                # 动画结束后恢复正常布局
                event_label.place_forget()
                event_label.pack(anchor=tk.W, pady=2)

        slide_in()
        event_counter += 1

    def update_time():
        nonlocal prev_minutes, prev_seconds, current_minute_text, current_second_text
        elapsed = int(time.time()) - start_time
        minutes = elapsed // 60
        seconds = elapsed % 60

        # 更新时间滚动
        prev_minutes, current_minute_text = scroll_element(
            minute_canvas, minutes, "#FF0000", prev_minutes, current_minute_text
        )
        prev_seconds, current_second_text = scroll_element(
            second_canvas, seconds, "#FFFF00", prev_seconds, current_second_text
        )

        # 检查是否需要显示新事件
        if elapsed in timed_events and elapsed not in displayed_events:
            add_event_text(timed_events[elapsed])
            displayed_events.add(elapsed)

        root.after(100, update_time)

    # 初始化显示
    current_minute_text = minute_canvas.create_text(
        element_width / 2, element_height * 0.7, text="0", font=custom_font, fill="#FF0000"
    )
    current_second_text = second_canvas.create_text(
        element_width / 2, element_height * 0.7, text="0", font=custom_font, fill="#FFFF00"
    )

    update_time()

    # 窗口位置（右上角）
    root.update_idletasks()
    screen_width = root.winfo_screenwidth()
    window_width = root.winfo_width()
    root.geometry(f"+{screen_width - window_width}+100")

    # 退出功能
    def on_escape(event):
        root.destroy()

    root.bind("<Escape>", on_escape)
    root.bind("<Double-1>", on_escape)

    root.mainloop()


if __name__ == "__main__":
    show_classification_text()
